
package com.ruhua.java.service;

import com.ruhua.java.dao.BannerItem;
import com.ruhua.java.dto.BannerDTO;
import com.ruhua.java.exception.NotFoundException;
import com.ruhua.java.exception.TrowException;
import com.ruhua.java.repository.BannerItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service
public class BannerItemService {
    @Autowired
    BannerItemRepository bannerItemRepository;

    public BannerItem getById(Long num) {
        BannerItem banner = bannerItemRepository.findOneById(num);
        if(banner == null){
            throw new NotFoundException(10001);
        }
        return banner;
    }


    public List<BannerItem> getBannerItemList() {
        return this.bannerItemRepository.findAll();
    }


    public void createItem(BannerDTO bannerDTO) {
        BannerItem item = BannerItem.builder()
                .jumpId(bannerDTO.getJumpId())
                .bannerId(bannerDTO.getBannerId())
                .keyWord(bannerDTO.getKeyWord())
                .imgId(bannerDTO.getImgId())
                .type(bannerDTO.getType())
                .build();
        bannerItemRepository.save(item);
    }

    public void updateItem(Map person) {
        String sid=person.get("id").toString();
        Long id=Long.parseLong(sid);
        BannerItem item = this.getById(id);
        String keyWord = person.get("key_word").toString();
        Integer imgId = (Integer)person.get("img_id");
        if (item == null && keyWord == null) {
            throw new TrowException("参数错误");
        }
        item.setKeyWord(keyWord);
        item.setImgId(imgId);
        item.setType(person.get("type").toString());
        bannerItemRepository.save(item);
    }

    public void delItem(Long id) {
        try {
            bannerItemRepository.deleteById(id);
        } catch (Exception e) {
            throw new NotFoundException(10001);
        }
    }
}
